package com.example.idea.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import com.example.idea.utils.AuthAccess;
import com.example.idea.utils.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 功能
 * 作者：妙笔生花
 * 日期：2024/9/9 14:21
 */
@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${ip:localhost}")
    private String ip;

    @Value("${server.port}")
    private String port;

    private static final String FILE_NAME = System.getProperty("user.dir") + File.separator + "files";

    @AuthAccess
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return Result.failure("文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        String mainName = FileUtil.mainName(originalFilename);
        String extName = FileUtil.extName(originalFilename);

        if (!FileUtil.exist(FILE_NAME)) {
            FileUtil.mkdir(FILE_NAME);
        }

        String saveFileName = originalFilename;
        if (FileUtil.exist(FILE_NAME + File.separator + originalFilename)) {
            saveFileName = System.currentTimeMillis() + "_" + mainName + "." + extName;
        }

        File saveFile = new File(FILE_NAME + File.separator + saveFileName);
        file.transferTo(saveFile);

        String url = "http://" + ip + ":" + port + "/file/download/" + saveFileName;
        return Result.success(url);
    }

    @AuthAccess
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        String filePath = FILE_NAME + File.separator + fileName;
        if (!FileUtil.exist(filePath)) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "文件不存在");
            return;
        }

        byte[] bytes = FileUtil.readBytes(filePath);
        response.setContentType("application/octet-stream");
        response.setContentLength(bytes.length);
        String encodedFileName = java.net.URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
    }

    /**
     * 富文本上传图片
     * @param file
     * @return
     * @throws IOException
     */
    @AuthAccess
    @PostMapping("/editor/upload")
    public Dict uploadImg(@RequestParam("file") MultipartFile file, @RequestParam String type) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String mainName = FileUtil.mainName(originalFilename);
        String extName = FileUtil.extName(originalFilename);
        if (!FileUtil.exist(FILE_NAME)) {
            FileUtil.mkdir(FILE_NAME);
        }
        String saveFileName = originalFilename;
        if (FileUtil.exist(FILE_NAME + File.separator + originalFilename)) {
            saveFileName = System.currentTimeMillis() + "_" + mainName + "." + extName;
        }
        File saveFile = new File(FILE_NAME + File.separator + saveFileName);
        file.transferTo(saveFile);
        String url = "http://" + ip + ":" + port + "/file/download/" + saveFileName;
        if ("img".equals(type)) {
            return Dict.create().set("errno",0).set("data", CollUtil.newArrayList(Dict.create().set("url", url)));
        } else if("video".equals(type)) {
            return Dict.create().set("errno",0).set("data", Dict.create().set("url", url));
        }
        return Dict.create().set("errno",0);
    }
}
